<template>
  <el-form :model="form" ref="form">
    <div class="mb20">
      <zm-button @click="add">添加</zm-button>
    </div>
    <zm-table :data="form.list">
      <zm-table-column prop="startDay" label="回款天数起点(天)">
        <template slot-scope="{ row, $index }">
          <el-form-item :prop="`list.${$index}.startDay`" :rules="ruleItem">
            <el-input
              v-model="row.startDay"
              placeholder="请输入正整数"
            ></el-input>
          </el-form-item>
        </template>
      </zm-table-column>
      <zm-table-column prop="endDay" label="逾期天数终点(天)">
        <template slot-scope="{ row, $index }">
          <el-form-item :prop="`list.${$index}.endDay`" :rules="ruleItem">
            <el-input
              v-model="row.endDay"
              placeholder="请输入正整数"
            ></el-input>
          </el-form-item>
        </template>
      </zm-table-column>
      <zm-table-column prop="proportion" label="发放提成比例(%)">
        <template slot-scope="{ row, $index }">
          <el-form-item
            :prop="`list.${$index}.proportion`"
            :rules="percentRule"
          >
            <el-input
              v-model="row.proportion"
              placeholder="至多两位小数的正数"
              :readonly="$index === 0"
            >
              <template slot="append">
                %
              </template>
            </el-input>
          </el-form-item>
        </template>
      </zm-table-column>
      <zm-table-column prop="proportion" label="操作" fixed="right" width="150">
        <template slot-scope="scope">
          <a href="javascript:;" @click="onDelete(scope)">{{scope.$index===0?'--':'删除'}}</a>
        </template>
      </zm-table-column>
    </zm-table>
  </el-form>
</template>

<script>
import validataRules from '@/utils/validateRule'
const itemModel = JSON.stringify({ startDay: '', endDay: '', proportion: '' })
export default {
  name: 'RuleTable',
  components: {},
  model: {
    prop: 'list',
    event: 'change'
  },
  props: {
    list: {
      type: Array,
      default: () => {
        return [...JSON.parse(itemModel)]
      }
    }
  },
  data () {
    const integer = (rule, value, cb) => {
      if (!value || !/^[1-9]{1,}[\d]*$/.test(value)) {
        cb(new Error('请输入正整数!'))
      } else {
        cb()
      }
    }
    return {
      ruleItem: [
        {
          validator: integer,
          trigger: 'blur'
        }
      ],
      percentRule: [
        { required: true, message: '请输入比例', trigger: 'blur' },
        {
          validator: validataRules.stringNumber,
          trigger: 'blur'
        }
      ]
    }
  },
  computed: {
    form: {
      get () {
        return {list: [...this.list]}
      },
      set (val) {
        this.$emit('change', val.list)
      }
    }
  },
  watch: {
    // list (val) {
    //   console.log('ival', val)
    //   this.form.list = val
    // },
    // form: {
    //   handler (val) {
    //     console.log('val', val.list)
    //     this.$emit('change', val.list)
    //   },
    //   deep: true
    // }
  },
  mounted () {
    this.form.list = [...this.list]
  },
  methods: {
    add () {
      /* if (this.form.list.length === 10) {
        return this.$msg.warning('最多不超过10条')
      } */
      this.$emit('change', [...this.form.list, JSON.parse(itemModel)])
      // this.form.list.push(JSON.parse(itemModel))
    },
    ruleValidate () {
      let res = true // 是否有存在不符合情况
      const arr = this.form.list
      for (let key in arr) {
        const item = arr[key]
        const index = +key
        // 允许设置开始时间到结束时间段为相同数字，则视为仅当天，仅有1天
        if (+item.startDay > +item.endDay) {
          this.$msg.warning(
            `第${1 + index}条，时间设置错误，请设置连续有效时间`
          )
          console.log(item, index)
          res = false
          break
        } else if (index !== arr.length - 1) {
          if (+item.endDay + 1 !== +arr[index + 1].startDay) {
            this.$msg.warning(
              `第${index + 1}条与第${index +
                2}条，回款天数起点与逾期天数终点不连续`
            )
            console.log('SHANGX', item, index)
            res = false
            break
          }
        }
      }
      return res
    },
    onDelete ({ row, $index }) {
      console.log($index)
      if ($index === 0) return this.$msg.warning('最少一条')
      const list = [...this.form.list]
      list.splice($index, 1)
      this.$emit('change', [...list])
    },
    validate () {
      return new Promise((resolve, reject) => {
        let _valid = false
        this.$refs.form.validate(valid => {
          _valid = valid
        })
        if (!_valid) return reject()
        if (this.ruleValidate()) {
          return resolve()
        } else {
          return reject()
        }
      })
    }
  }
}
</script>
